class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    ListNode(int x, ListNode next) {
        val = x;
        this.next = next;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        ListNode node = this;
        while (node != null) {
            sb.append(node.val + "->");
            node = node.next;
        }
        return sb.toString();
    }
}

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode root = new ListNode(0);
        ListNode node1 = l1, node2 = l2, cur = root;
        int carry = 0;
        while (node1 != null || node2 != null) {
            int x = (node1 == null) ? 0 : node1.val;
            int y = (node2 == null) ? 0 : node2.val;
            int sum = x + y + carry;
            cur.next = new ListNode(sum >= 10 ? sum - 10 : sum);
            cur = cur.next;
            carry = sum / 10;
            if(node1 != null) node1 = node1.next;
            if(node2 != null) node2 = node2.next;
        }
        if(carry == 1) cur.next = new ListNode(1);
        return root.next;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        ListNode l2 = new ListNode(4);
        ListNode l3 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;
        ListNode l4 = new ListNode(5);
        ListNode l5 = new ListNode(6);
        ListNode l6 = new ListNode(4);
        l4.next = l5;
        l5.next = l6;
        ListNode res = new Solution().addTwoNumbers(l1, l4);
        System.out.println(res);
    }
}